<template>
  <div>
    <el-button type="primary" @click="showDialogByAdd">添加品牌</el-button>
    <!-- data相当于是当前表格的一个数据源 prop表示要渲染的属性-->
    <!-- <el-table border :data="tableData" style="width: 100%;margin:20px 0;"> -->
    <el-table v-loading="loading" border :data="trademarkList" style="width: 100%;margin:20px 0;">
      <el-table-column type="index" align="center" label="序号" width="60" />
      <el-table-column prop="tmName" align="center" label="品牌名称" width="150" />
      <el-table-column label="品牌LOGO" style="300">
        <template v-slot="{ row }">
          <!-- <p>{{ scoped.row }}</p> -->
          <img :src="row.logoUrl" :alt="row.tmName" style="width:100px">
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template v-slot="{row}">
          <el-button type="warning" icon="el-icon-edit" @click="editOneTrademark(row.id)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="delOneTrademark(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :current-page="currentPage" align="center" :page-sizes="[3,5,10,20]" :page-size="limit" layout=" prev, pager, next, jumper,->,sizes,total" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <el-dialog title="添加品牌" :visible.sync="dialogFormVisible">
      <el-form ref="tmForm" :model="tmForm" :rules="rules">
        <el-form-item label="品牌名称" label-width="90px" prop="tmName">
          <el-input v-model="tmForm.tmName" style="width:400px" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌Logo" label-width="90px" prop="logoUrl">
          <el-upload class="avatar-uploader" action="/dev-api/admin/product/fileUpload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" accept=".jpg,.png,.jpeg">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过3M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <!-- <el-button type="primary" @click="addOneTrademark">确 定</el-button> -->
        <el-button type="primary" @click="addOrUpdateOneTrademark">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { reqDeleteOneTrademark, reqGetOneTrademark, reqGetTrademarkList, reqSaveOneTrademark, reqUpdateOneTrademark } from '@/api/product/trademark'
export default {
  name: 'Trademark',
  data() {
    return {
      loading: false,
      currentPage: 1,
      limit: 5,
      total: 0,
      trademarkList: [],
      // 弹出框显示或是隐藏
      dialogFormVisible: false,
      imageUrl: '',
      tmForm: {
        // 品牌名称
        tmName: '',
        // 图片链接
        logoUrl: ''
      },
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        logoUrl: [{ required: true, message: '请选择一张品牌图片', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.getTrademarkList()
  },
  methods: {
    // 1. 获取当前的品牌数据列表
    async getTrademarkList() {
      const { currentPage: page, limit } = this
      this.loading = true
      const result = await reqGetTrademarkList(page, limit)
      // console.log(result)
      if (result.code === 200) {
        this.trademarkList = result.data.records
        this.total = result.data.total
        this.loading = false
      } else {
        this.$message.error('获取商品列表失败...')
      }
    },
    // 以下两个方法是分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.limit = val
      this.currentPage = 1
      this.getTrademarkList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getTrademarkList()
    },
    // 图片上传的方法
    // 上传成功后，会调用此方法
    handleAvatarSuccess(res, file) {
      console.log(res, file)
      // res是上传成功后，服务器响应回来的数据
      // file是一个大的对象，不但包含res中的内容还包含图片原有的数据(图片的名字，大小，格式...)
      this.imageUrl = URL.createObjectURL(file.raw)
      // this.imageUrl = res.data
      this.tmForm.logoUrl = res.data // 将上传图片成功后的图片链接地址存到这里面
      // 上传图片成功之后，移除校验提示
      this.$refs.tmForm.clearValidate(['logoUrl'])
    },
    // 上传之前会调用 此方法
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const imgArr = ['image/jpeg', 'image/jpg', 'image/png']
      const isJPG = imgArr.includes(file.type)
      // 1M=1024k  1K=1024byte
      const isLt3M = file.size / 1024 / 1024 < 3

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG、PNG、JPEG 格式!')
      }
      if (!isLt3M) {
        this.$message.error('上传头像图片大小不能超过 3MB!')
      }
      return isJPG && isLt3M
    },
    // 2. 添加一个品牌数据
    // async addOneTrademark() {
    addOrUpdateOneTrademark() {
      this.$refs['tmForm'].validate(async(valid) => {
        // console.log('valid', valid)
        if (valid) {
          // alert('submit!')
          let result
          // 此时可以根据tmForm中是否有id来判断,当前操作是更新还是添加
          // 有id是说明是更新 ，反之则是添加新trademark
          if (this.tmForm.id) {
            result = await reqUpdateOneTrademark(this.tmForm)
            // 再加一条 清空this.tmForm
          } else {
            result = await reqSaveOneTrademark(this.tmForm)
          }
          if (result.code === 200) {
            this.dialogFormVisible = false
            // 提示操作trademark成功
            this.$message.success('操作trademark成功...')
            // 刷新一下页面
            // this.currentPage = 1 // 查看第一页的数据
            this.getTrademarkList()
          } else {
            this.$message({
              type: 'error',
              message: '操作trademark失败...'
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 3. 删除
    delOneTrademark(id) {
      this.$confirm('您真的要删除此条数据吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const result = await reqDeleteOneTrademark(id)
          if (result.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 判断一下，是不是删除的最后一页的最后一条，如果是的话，则要显示前一页的数据
            this.currentPage = this.trademarkList.length === 1 ? this.currentPage - 1 : this.currentPage
            // 刷新当前页面
            this.getTrademarkList()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 4. 更新tradrmark之数据回显
    async editOneTrademark(id) {
      const result = await reqGetOneTrademark(id)
      if (result.code === 200) {
        this.dialogFormVisible = true
        // console.log(result)
        this.tmForm = result.data
        // 渲染图片
        this.imageUrl = result.data.logoUrl
      }
    },
    // 5. 单击添加按钮显示对话框并清空之前的内容
    showDialogByAdd() {
      this.tmForm.tmName = ''
      this.imageUrl = ''
      this.dialogFormVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
